from rest_framework.generics import ListAPIView, ListCreateAPIView

from meiduo_admin.utils import PageNum
from users.models import User

from meiduo_admin.serializers.users_serializer import UserSerializer, UserAddSerializer


class UserView(ListCreateAPIView):
    '''获取用户对象'''
    # serializer_class = UserSerializer
    pagination_class = PageNum  # 分页

    # queryset = User.objects.all()
    # 根据不同的请求方式返回不同序列化器
    def get_serializer_class(self):
        # 请求方式是GET，则是获取用户数据返回UserSerializer
        if self.request.method == 'GET':
            return UserSerializer
        else:
            # POST请求，完成保存用户，返回UserAddSerializer
            return UserAddSerializer

    def get_queryset(self):
        # 根据传递参数不同，传递不同数据
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            # 如果keyword为空查询所有数据
            return User.objects.all().order_by('id')

        else:
            return User.objects.filter(username__contains=keyword).order_by('id')
